package com.uplift.mgt.sys.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.uplift.common.Const;
import com.uplift.common.result.IResultable;
import com.uplift.common.result.ResultWrapper4Layui;
import com.uplift.common.utils.UUIDGenerater;
import com.uplift.mgt.sys.model.UploadModel;

/**
 * 富文本上传接口
 * 
 * @author bcwang
 *
 */
@Controller
@RequestMapping(value = "/upload")
public class UploadController {

	@RequestMapping(value = "/single")
	@ResponseBody
	public IResultable upload(UploadModel uploadModel, HttpServletRequest request, HttpServletResponse response) {
		try {
			CommonsMultipartFile cmf = uploadModel.getFile();
			FileItem ditem = cmf.getFileItem();
			String dfileName = ditem.getName();
			String dfileExt = dfileName.substring(dfileName.lastIndexOf(".")).toLowerCase();
			String dnewFileName = UUIDGenerater.generate() + dfileExt;
			String drfilePath = "common/";
			File dnewFileDir = new File(Const.DIR_UPLOAD_BASE, drfilePath);
			if (!dnewFileDir.exists()) {
				dnewFileDir.mkdirs();
			}
			File dfile = new File(dnewFileDir, dnewFileName);
			ditem.write(dfile);

			String relatePath = drfilePath + dnewFileName;

			Map<String, String> dataMap = new HashMap<>();
			String serverName = request.getScheme() + "://" + request.getServerName();
			if (80 == request.getServerPort()) {
				serverName += "/static-files/";
			} else {
				serverName += ":" + request.getServerPort() + "/static-files/";
			}
			dataMap.put("src", serverName + relatePath);
			dataMap.put("title", "");

			return ResultWrapper4Layui.wrapMap(dataMap, ResultWrapper4Layui.FAIL, "上传成功");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultWrapper4Layui.wrapMap(null, ResultWrapper4Layui.SUCC, "上传失败");
		}
	}
}
